<template>
  <div class="container">
    <div ref="searchRef">
      <el-form :inline="true" :model="params" class="grids gridColumns5">
        <el-form-item label="开班时间">
          <DatePicker v-model="params.classOpeningTime"></DatePicker>
        </el-form-item>
        <el-form-item label="班级名称">
          <el-input
            v-model="params.className"
            placeholder="班级名称"
            clearable
            @change="onSubmit"
          />
        </el-form-item>
        <el-form-item label="班级老师">
          <accountSelect v-model="params.classTeacherId"></accountSelect>
        </el-form-item>
        <el-form-item label="授课地点">
          <dictSelect
            v-model="params.classAddress"
            multiple="1"
            dictCode="teaching_location"
          ></dictSelect>
        </el-form-item>
        <el-form-item label="班级状态">
          <el-select
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="2"
            multiple
            v-model="params.status"
            placeholder="班级状态"
            clearable
            @change="onSubmit"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in classStateOptions"
              :key="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联课程">
          <courseQuery v-model="params.curriculumId" multiple="1"></courseQuery>
        </el-form-item>
        <el-form-item label="授课老师">
          <el-input
            v-model="params.teachingTeacher"
            placeholder="授课老师"
            clearable
            @change="onSubmit"
          />
        </el-form-item>
        <el-form-item label="班级编号">
          <el-input
            v-model="params.classId"
            placeholder="班级编号"
            clearable
            @change="onSubmit"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="init">重置</el-button>
          <el-button
            type="primary"
            @click="proxy.$refs.addClassRef.open()"
            plain
            >新增班级</el-button
          >
        </el-form-item>
      </el-form>
      <div class="actionBtn">
        <!-- <el-button type="primary" @click="proxy.$refs.addClassRef.open()">新增班级</el-button>
        <el-button @click="">批量结业</el-button>
        <el-button @click="">导出班级</el-button> -->
      </div>
    </div>

    <el-table
      :max-height="tableHeight"
      :data="tableData.rows"
      v-loading="loading"
    >
      <el-table-column prop="classOpeningTime" label="开班时间" width="170" />
      <el-table-column
        prop="className"
        label="班级名称"
        :width="classNameWidth"
      >
        <template #default="scope">
          <div
            @click="
              proxy.$utils.toLink(
                `/classManage/classDetails?classId=${scope.row._id}`
              )
            "
            class="className"
          >
            {{ scope.row.className }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="授课地点" width="250">
        <template #default="scope">
          <dictSelect
            readonly="1"
            v-model="scope.row.classAddress"
            dictCode="teaching_location"
          ></dictSelect>
        </template>
      </el-table-column>
      <el-table-column prop="classId" label="班级编号" width="130" />
      <el-table-column
        prop="classTeacher_Info.userName"
        label="班级老师"
        width="100"
      />
      <el-table-column prop="teachingTeacher" label="授课讲师" width="100" />
      <el-table-column prop="classNum" label="班级人数" width="100">
        <template #default="scope">
          <div class="flex">
            {{ students_format(scope.row, "all") }}
            <div class="button" style="margin-left: 2px">
              ({{ students_format(scope.row, "isSubmit") }})
            </div>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="classHours" label="班级课时" width="100" /> -->
      <el-table-column prop="address" label="排班课时" width="100">
        <template #default="scope">
          {{ unitClassHours_format(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="已授课时" width="100">
        <template #default="scope">
          {{ lesson_hours_format(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="已授节数" width="100">
        <template #default="scope">
          {{
            scope.row.teaching_signInComplete
              ? scope.row.teaching_signInComplete.length
              : 0
          }}
          / {{ scope.row.classDates ? scope.row.classDates.length : 0 }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="班级状态"
        width="100"
        fixed="right"
      >
        <template #default="scope">
          <el-text type="warning" v-if="scope.row.status == 0">待开班</el-text>
          <el-text type="success" v-else-if="scope.row.status == 1"
            >开班</el-text
          >
          <el-text type="info" v-else>结业</el-text>
        </template>
      </el-table-column>
      <el-table-column
        prop="course_Info.name"
        label="关联课程"
        width="450"
        show-overflow-tooltip
      />
      <el-table-column label="操作" width="230" align="center" fixed="right">
        <template #default="scope">
          <div class="flex alignCenter">
            <div class="actionText" @click="handleClick(scope.row, 1)">
              班级学员
            </div>
            <el-divider direction="vertical" class="line" />
            <div class="actionText" @click="handleClick(scope.row, 2)">
              签到情况
            </div>
            <el-divider direction="vertical" class="line" />
            <el-dropdown>
              <div class="flex alignCenter">
                <div class="actionText">更多</div>
                <el-icon><arrow-down /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    @click="handleClick(scope.row, 3)"
                    :disabled="
                      !scope.row.classTeacherId || scope.row.status == 2
                    "
                    >结业</el-dropdown-item
                  >
                  <el-dropdown-item
                    @click="handleClick(scope.row, 4)"
                    :disabled="
                      !scope.row.classTeacherId && scope.row.status == 0
                    "
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-if="tableData['total']"
      :total="tableData['total']"
      v-model:page="params.pageIndex"
      v-model:limit="params.pageSize"
      @pagination="getInfo"
    />

    <updateClass ref="addClassRef" @fatherMethod="getInfo"></updateClass>
  </div>
</template>

<script setup lang="ts">
import updateClass from "@/views/courseManage/components/updateClass.vue";
const { proxy } = getCurrentInstance();
//counter
import useCounterStore from "@/store/counter";
const counter = useCounterStore();

let classStateOptions = ref([
  { label: "待开班", value: 0 },
  { label: "开班", value: 1 },
  { label: "结业", value: 2 },
]);

let params = ref({
  classOpeningTime: "",
  className: "",
  classTeacherId: "",
  classAddress: "",
  status: "",
  curriculumId: "", //关联课程
  teachingTeacher: "", //授课老师
  pageIndex: 1,
  pageSize: 50,
  classId: "",
});
let tableData = ref({});
let classNameWidth = ref(0);
let loading = ref(false);
let searchHeight = ref(0);

let tableHeight = computed(() => {
  let hei =
    window.innerHeight - 84 - counter.pageHeight - 55 - searchHeight.value;
  return `${hei}px`;
});

onMounted(() => {
  getInfo();
  searchHeight.value = proxy.$refs.searchRef.offsetHeight;
});

//班级人数
function students_format(e, type) {
  if (!e.class_students) return;
  let all = e.class_students.length || 0;
  let isSubmit = e.class_students.filter((item) => item.isSubmit).length || 0;
  return type == "all" ? all : isSubmit;
}

function onSubmit() {
  params.value.pageIndex = 1;
  getInfo();
}

function unitClassHours_format(item) {
  let { teaching_scheduling, classHours } = item;
  if (!teaching_scheduling) return;
  let total_hours = 0;
  teaching_scheduling.forEach((element) => {
    if (element.unitClassHours) total_hours += element.unitClassHours;
  });
  return `${total_hours} / ${classHours}`;
}

function lesson_hours_format(item) {
  let { teaching_signInComplete, classHours } = item;
  if (!teaching_signInComplete) return `0 / ${classHours}`;
  let total_hours = 0;
  teaching_signInComplete.forEach((element) => {
    if (teaching_signInComplete) total_hours += element.unitClassHours;
  });
  return `${total_hours} / ${classHours}`;
}

async function handleClick(row, num) {
  try {
    if (!counter.isShowActionBtn(row)) return;
    switch (num) {
      case 1:
        proxy.$utils.toLink(
          `/classManage/classDetails?classId=${row._id}&current=2`
        );
        break;
      case 2:
        proxy.$utils.toLink(
          `/classManage/classDetails?classId=${row._id}&current=3`
        );
        break;
      case 3: //结业
        let ret = await proxy.$utils.confirmTips("是否确认结业?");
        if (!ret) return;
        // let res = await proxy.$apis.classStudent({
        //   type: "query",
        //   data: { classId: row._id },
        // });
        // let hasScore = false;
        // res.forEach((element) => {
        //   if (element.theory || element.practicalTraining) hasScore = true;
        // });
        // if (!hasScore) return proxy.$utils.showToast("请先录入学生成绩", 0);
        // let rew = await counter.studentInfo(row._id);
        // let hasStudentAddress = false;
        // rew.forEach((element) => {
        //   if (element.address) hasStudentAddress = true;
        // });
        // if (!hasStudentAddress)
        //   return proxy.$utils.showToast("请完善B3学员信息表");
        await proxy.$apis.classData({
          type: "graduation",
          data: { _id: row._id },
        });
        proxy.$utils.showToast("结业成功");
        getInfo();
        break;
      case 4:
        let resp = await proxy.$utils.confirmTips("是否确认删除该班级?");
        if (!resp) return;
        await proxy.$apis.classData({
          type: "del",
          data: { _id: row._id },
        });
        proxy.$utils.showToast("删除成功");
        getInfo();
        break;
      default:
        break;
    }
  } catch (error) {
    console.log("error", error);
  }
}

async function getInfo() {
  try {
    loading.value = true;
    tableData.value = await proxy.$apis.classData({
      type: "list",
      data: params.value,
    });
    console.log("tableData.value", tableData.value);

    let fieldNameLength = await proxy.$apis.classData({
      type: "longest",
    });
    classNameWidth.value = fieldNameLength.data[0].length * 15;
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function init() {
  params.value = {
    classOpeningTime: "",
    className: "",
    classTeacherId: "",
    classAddress: "",
    status: "",
    curriculumId: "", //关联课程
    teachingTeacher: "", //授课老师
    pageIndex: 1,
    pageSize: 50,
    classId: "",
  };
  getInfo();
}

watch(
  () => [
    params.value.classOpeningTime,
    params.value.classTeacherId,
    params.value.classAddress,
    params.value.curriculumId,
  ],
  (newValue, oldValue) => {
    if (newValue) onSubmit();
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.container {
  margin: 20px;
  .actionBtn {
    margin-bottom: 20px;
  }
  .actionText {
    cursor: pointer;
    color: var(--el-color-primary);
    font-size: 14px;
    white-space: nowrap;
  }
  .line {
    height: 20px;
  }
  .className {
    cursor: pointer;
    color: #ca5f20;
  }
}
</style>
